package org.sharding.config;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingValue;

import java.math.BigInteger;
import java.util.Collection;

public class MyPreciseTableShardingAlgorithm implements PreciseShardingAlgorithm<Long> {

    /**
     * @param collection           表示可选的数据源值 - 这里对应的是 数据表名 集合
     * @param preciseShardingValue 分片键对应的值
     */
    @Override
    public String doSharding(Collection<String> collection, PreciseShardingValue<Long> preciseShardingValue) {
        // 主键名称
        String columnName = preciseShardingValue.getColumnName();
        // 主键值
        Long value = preciseShardingValue.getValue();
        // 实现分片算法 course$->{cid % 2 + 1}
        BigInteger bigInteger = Convert.toBigInteger(value);
        BigInteger add = bigInteger.mod(Convert.toBigInteger(2)).add(Convert.toBigInteger(1));

        // 获取逻辑表的名称
        String logicTableName = preciseShardingValue.getLogicTableName();
        // 拼接成真实表
        String tableName = StrUtil.format("{}_{}", logicTableName, add);
        if (collection.contains(tableName)) {
            return tableName;
        }
        throw new RuntimeException("不存在的数据包");
    }
}
